import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {PublicService} from '../../services/public.service';
import {MessageService} from 'primeng/components/common/messageservice';
import {ConfirmationService, TreeNode} from 'primeng/primeng';
import {BasePage} from '../../base.page';
import {CabinetModel} from "../cabinet.model";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-cap-cabinet',
  templateUrl: './cap-cabinet.component.html',
  styleUrls: ['./cap-cabinet.component.scss']
})
export class CapCabinetComponent extends BasePage implements OnInit {
    title: string = '新增机柜列';
    myForm: FormGroup;
    types: Array<object>;
    displaycabinet: boolean;
    cabinetObj: CabinetModel;
    treeDatas: TreeNode[];
    selected: any;
    paramDid: string;

    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private publicService: PublicService,
                public messageService: MessageService,
                private eventBusService: EventBusService,
                public confirmationService: ConfirmationService) {
        super(confirmationService, messageService);
    }

    ngOnInit() {
        this.cabinetObj = new CabinetModel();
        this.initForm();
        this.initType();
        this.initDatas();
        this.getRouterParam();
        this.getFather();
    }
    initForm(): void {
        this.myForm = this.fb.group({
            father: '',
            name: '',
            planning_power: '',
            planning_rack: '',
            planning_pdu: '',
            planning_network_port: ''
        });
    }
    initDisplay(): void {
        this.displaycabinet = false;
    }
    initType(): void {
        this.types = [
            {label: '普通机房', value: 'common'},
            {label: '模块化机房', value: 'module'},
            {label: '微模块机房', value: 'micmodule'},
            {label: '空调间', value: 'air'},
            {label: '电力间', value: 'power'},
            {label: '设施间', value: 'facility'},

        ];
    }
    onHide(type): void {
        (type === 'cabinet') && (this.displaycabinet = false);
    }
    show(type): void {
        (type === 'cabinet') && (this.displaycabinet = true);
        this.initTreeDatas();
    }
    hide(type): void {
        this.onHide(type);
    }
    sure(type): void {
        this.onHide(type);
        this.cabinetObj.father = this.selected['label'];
        this.cabinetObj.father_did = this.selected['did'];
    }
    cancel(type): void {
        this.onHide(type);
    }
    clear() {
        this.cabinetObj.father = '';
        this.cabinetObj.father_did = '';
    }
    initDatas() {
        this.activedRouter.queryParams.subscribe(param => {
            if (param['did']) {
                this.title = '编辑机柜列信息';
                this.publicService.getSingleNode(param['did']).subscribe(res => {
                   this.cabinetObj = new CabinetModel(res);
                });
            }
        });
    }
    initTreeDatas() {
        this.publicService.getCapBasalDatas('', this.cabinetObj.sp_type).subscribe(res => {
            this.treeDatas = res;
        });
    }
    get father() {
        return this.myForm.controls['father'].untouched && this.myForm.controls['father'].hasError('required');
    }
    get name() {
        return this.myForm.controls['name'].untouched && this.myForm.controls['name'].hasError('required');
    }
    get planning_power() {
        return this.myForm.controls['planning_power'].untouched && this.myForm.controls['planning_power'].hasError('required');
    }
    get planning_pdu() {
        return this.myForm.controls['planning_pdu'].untouched && this.myForm.controls['planning_pdu'].hasError('required');
    }
    get planning_rack() {
        return this.myForm.controls['planning_rack'].untouched && this.myForm.controls['planning_rack'].hasError('required');
    }
    get planning_network_port() {
        return this.myForm.controls['planning_network_port'].untouched && this.myForm.controls['planning_network_port'].hasError('required');
    }
    save() {
        if (this.cabinetObj['name'] &&
            this.cabinetObj['father'] &&
            this.cabinetObj['planning_power'] &&
            this.cabinetObj['planning_pdu'] &&
            this.cabinetObj['planning_rack'] &&
            this.cabinetObj['planning_network_port']) {
            if (this.paramDid) {
                this.publicService.editCabinet(this.cabinetObj).subscribe(res => {
                    if (res === '00000'){
                        this.alert('编辑成功');
                        this.eventBusService.space.next(true);
                        this.router.navigate(['../../capacityBasalDatas'], {queryParams: {did: this.cabinetObj['father_did']}, relativeTo: this.activedRouter});
                    }else {
                        this.alert('编辑失败', 'error');
                    }
                });
            }else {
                this.publicService.addCabinet(this.cabinetObj).subscribe(res => {
                    if (res === '00000') {
                        this.alert('新增成功');
                        this.eventBusService.space.next(true);
                        this.router.navigate(['../../capacityBasalDatas'], {queryParams: {did: this.cabinetObj['father_did']}, relativeTo: this.activedRouter});
                    }else {
                        this.alert(`新增失败: ${res}`, 'error');
                    }
                });
            }
        }else {
            this.setValidators();
            this.alert('请填写完整信息', 'warn');
        }

    }
    goBack() {
        this.router.navigate(['../../capacityBasalDatas'], {relativeTo: this.activedRouter});
    }
    setValidators() {
        this.myForm.controls['name'].setValidators([Validators.required]);
        this.myForm.controls['father'].setValidators([Validators.required]);
        this.myForm.controls['planning_power'].setValidators([Validators.required]);
        this.myForm.controls['planning_rack'].setValidators([Validators.required]);
        this.myForm.controls['planning_pdu'].setValidators([Validators.required]);
        this.myForm.controls['planning_network_port'].setValidators([Validators.required]);
        this.myForm.controls['name'].updateValueAndValidity();
        this.myForm.controls['father'].updateValueAndValidity();
        this.myForm.controls['planning_power'].updateValueAndValidity();
        this.myForm.controls['planning_rack'].updateValueAndValidity();
        this.myForm.controls['planning_pdu'].updateValueAndValidity();
        this.myForm.controls['planning_network_port'].updateValueAndValidity();
    }
    getFather() {
        this.activedRouter.queryParams.subscribe(param => {
            this.cabinetObj['father'] = param['father'];
            this.cabinetObj['father_did'] = param['father_did'];
            this.cabinetObj['sp_type'] = param['sp_type'];
        });
    }
    getRouterParam(){
        this.activedRouter.queryParams.subscribe(param => {
            this.paramDid = param['did'];
        });
    }

}
